<template>
	<view class="content">
		<view class="cropper-wrapper" style="height:617px">
			<canvas
				class="cropper"
				disable-scroll="true"
				@touchstart="touchStart"
				@touchmove="touchMove"
				@touchend="touchEnd"
				:style="{ width: cropperOpt.width, height: cropperOpt.height }"
				canvas-id="cropper"
			></canvas>
		</view>
		<view class="cropper-buttons">
			<view class="upload" @tap="uploadTap">重新选择</view>
			<view class="getCropperImage" @tap="getCropperImage" :disabled="buttonDisabled">确定</view>
		</view>
	</view>
</template>

<script>
import weCropper from '@/static/js/weCropper';
const device = uni.getSystemInfoSync();
const width = device.windowWidth;
const height = device.windowHeight - 50;
export default {
	data() {
		return {
			cropperOpt: {
				id: 'cropper',
				width: width,
				height: height,
				scale: 2.5,
				zoom: 8,
				cut: {
					x: (width - 200) / 2,
					y: (height - 200) / 2,
					width: 200,
					height: 200
				}
			},
			weCropper: '',
			uploadUrl:'',
			buttonDisabled:true,
			userInfo:{userId:'',},
		};
	},
	created(){
		this.userInfo=uni.getStorageSync('userInfo');
		this.uploadUrl=this.$http.adornUrl(this.$api.avatarEdit);
	},
	methods: {
		touchStart(e) {
			this.weCropper.touchStart(e);
		},
		touchMove(e) {
			this.weCropper.touchMove(e);
		},
		touchEnd(e) {
			this.weCropper.touchEnd(e);
		},
		convertBase64UrlToBlob(dataURI, type) {
			var binary = atob(dataURI.split(',')[1]);
			var array = [];
			for (var i = 0; i < binary.length; i++) {
				array.push(binary.charCodeAt(i));
			}
			return new Blob([new Uint8Array(array)], { type: type }, { filename: '1111.jpg' });
		},
		blobToDataURL(blob) {
			var a = new FileReader();
			a.readAsDataURL(blob); //读取文件保存在result中
			a.onload = function(e) {
				var getRes = e.target.result; //读取的结果在result中
				console.log(getRes);
			};
		},
		getCropperImage() {
			const that = this;
			this.weCropper.getCropperImage(avatar => {
				if (avatar) {
					/* uni.redirectTo({
						url: '/pages/avatar-edit/avatar-edit?avatar=' + avatar
					}); */
					that.buttonDisabled = true;
					uni.showLoading({title:'loading'})
					uni.uploadFile({
						url: that.uploadUrl,
						filePath: avatar,
						name: 'file',
						header: {
							'token': uni.getStorageSync('token')?uni.getStorageSync('token'):"false"
						},
						formData: { userId: that.userInfo.userId},
						success: (res) => {
							if (res.statusCode == 200 && res.data) {
								var data = JSON.parse(res.data);
								if (data.code == 401) {// 401, token失效
									var token = '';
									uni.setStorageSync('token', token);
									//需要登录后才可以操作
									uni.showModal({
										title: '',
										content: '请重新登录',
										success: function (res) {
											if (res.confirm) {
												uni.redirectTo({url:"/pages/login/login"});
											}
										}
									});
								} else if(data.code == 0){
									uni.setStorageSync('userInfo', data.data);
									this.$store.commit('user/updateUserInfo', data.data);
									uni.navigateBack({delta: 1});
								} else {
									that.buttonDisabled = false;
									uni.showToast({
										title: 'err!请重试'
									});
								}
							} else {
								that.buttonDisabled = false;
								uni.showToast({
									title: 'err!请重试'
								});
							}
						},
						fail: (res) => {
							that.buttonDisabled = false;
							uni.showToast({
								title: 'err!请重试'
							});
						},
						complete: function () {
							uni.hideLoading();
						},
					});
				} else {
					console.log('获取图片失败，请稍后重试');
				}
			});
		},
		uploadTap() {
			const self = this;

			uni.chooseImage({
				count: 1, // 默认9
				sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success(res) {
					let src = res.tempFilePaths[0];
					//  获取裁剪图片资源后，给data添加src属性及其值

					self.weCropper.pushOrign(src);
				}
			});
		}
	},
	onLoad(option) {
		// do something
		const cropperOpt = this.cropperOpt;
		const src = option.src;
		if (src) {
			Object.assign(cropperOpt, {
				src
			});

			this.weCropper = new weCropper(cropperOpt)
				.on('ready', function(ctx) {})
				.on('beforeImageLoad', ctx => {
					uni.showToast({
						title: '上传中',
						icon: 'loading',
						duration: 3000
					});
				})
				.on('imageLoad', ctx => {
					uni.hideToast();
				});
		}
	}
};
</script>

<style>
	.content {
		height:100%;
		background: rgba(0, 0, 0, 1);
	}
	
	.cropper-wrapper {
		position: relative;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		background-color: #000;
	}
	
	.cropper {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}

	.cropper-buttons {
		background-color: rgba(0, 0, 0, 0.95);
		color: #fff;
		width: 100%;
		height: 50px;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		position: fixed;
		bottom: 0;
		left: 0;
		line-height: 50px;
	}

	.cropper-buttons .upload,
	.cropper-buttons .getCropperImage {
		width: 50%;
		text-align: center;
	}
</style>